<template>
    <div class="login-container">
        <div class="login-box">
            <h2 class="login-title">用户登录</h2>
            <!-- @submit 是 Vue 的事件监听语法（等同于 v-on:submit） -->
            <!-- prevent阻止表单的默认提交行为（即阻止页面刷新） -->
            <!-- :class="{ 'is-invalid': errors.username }是 Vue 的 v-bind:class 的简写，（: 等同于 v-bind:）,它会根据条件决定是否添加某个 CSS 类 
            后面style中是  .form-group input.is-invalid-->
            <form @submit.prevent="handleSubmit" class="login-form">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="form.username" placeholder="请输入用户名"
                        :class="{ 'is-invalid': errors.username }" />
                    <div class="invalid-feedback" v-if="errors.username">
                        {{ errors.username }}
                    </div>
                </div>

                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="form.password" placeholder="请输入密码"
                        :class="{ 'is-invalid': errors.password }" />
                    <div class="invalid-feedback" v-if="errors.password">
                        {{ errors.password }}
                    </div>
                </div>

                <div class="form-options">
                    <label class="remember-me">
                        <input type="checkbox" v-model="form.remember" />
                        记住我
                    </label>
                    <a href="#" class="forgot-password">忘记密码?</a>
                </div>
                <!-- v-bind:disabled 当 loading 为 true 时，禁用该元素；当 loading 为 false 时，启用该元素。
                后面style是  .login-button:disabled -->
                <button type="submit" class="login-button" :disabled="loading">
                    <span v-if="!loading">登录</span>
                    <span v-else>登录中...</span>
                </button>
            </form>

            <div class="login-footer">
                没有账号? <a href="#" @click.prevent="$emit('switch-to-register')">立即注册</a>
            </div>
        </div>
    </div>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
    name: 'LoginForm',
    data() {
        return {
            form: {
                username: '',
                password: '',
                remember: false
            },
            errors: {
                username: '',
                password: ''
            },
            loading: false
        }
    },
    methods: {
        ...mapMutations(['SET_USERNAME']),
        validateForm() {
            let isValid = true

            // 重置错误信息
            this.errors = { username: '', password: '' }

            // 验证用户名,用于检查表单中的用户名是否为空或仅包含空白字符
            if (!this.form.username.trim()) {
                this.errors.username = '请输入用户名'
                isValid = false
            }

            // 验证密码
            if (!this.form.password) {
                this.errors.password = '请输入密码'
                isValid = false
            } else if (this.form.password.length < 6) {
                this.errors.password = '密码长度不能少于6位'
                isValid = false
            }

            return isValid
        },
        async handleSubmit() {
            if (!this.validateForm()) return;

            this.loading = true;

            try {
                const response = await fetch('http://localhost:3000/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: this.form.username,
                        password: this.form.password
                    })
                });
                const data = await response.json();
                console.log(data);

                // 检查 HTTP 状态码
                if (!response.ok) {
                    // 如果状态码不是 2xx，抛出错误
                    throw new Error(data.message || '登录失败');
                }

                // 登录成功
                console.log('登录成功:', data);
                this.SET_USERNAME(data.data.user.username) // 存用户名到vuex
                this.$router.push('/user/profile'); // ✅ 使用 this.$router
            } catch (error) {
                console.error('登录失败:', error);
                this.errors.password = error.message || '登录失败，请重试';
            } finally {
                this.loading = false;
            }
        }
    }
}
</script>

<style scoped>
/* 登录框位置 */
.login-container {
    display: flex;
    /* 水平居中 */
    justify-content: center;
    /* 垂直居中 */
    align-items: center;
    /* 背景占整个高度，而不是根据文字来确定高度 */
    min-height: 100vh;
    /* 它会创建一个从颜色 #a1c4fd 渐变到 #c2e9fb 的平滑过渡背景 */
    background-image: linear-gradient(120deg, #5d88cc 0%, #d7f2ff 100%);
}

/* 登录框大小 */
.login-box {
    width: 400px;
    padding: 2rem;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
    text-align: center;
    margin-bottom: 1.5rem;
    color: #333;
}

/* 子元素为用户名和密码两大块的div，主轴为y轴 */
.login-form {
    display: flex;
    flex-direction: column;
    gap: 1.2rem;
}

/* 子元素为大块中的小块，比如title,输出框，错误提示，主轴为y轴 */
.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-group label {
    font-weight: 500;
    color: #555;
}

/* 输入框 */
.form-group input {
    padding: 0.75rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    transition: border-color 0.3s;
}

/* 输入框获得焦点时，添加阴影 */
.form-group input:focus {
    border-color: #4285f4;
    outline: none;
    box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}

/* 根据条件决定是否添加某个 CSS 类 */
.form-group input.is-invalid {
    border-color: #ff4444;
}

/* 错误信息 */
.invalid-feedback {
    color: #ff4444;
    font-size: 0.85rem;
    margin-top: 0.25rem;
}

/* 记住我、忘记密码行 */
.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.9rem;
}

.remember-me {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #555;
}

.forgot-password {
    color: #4285f4;
    text-decoration: none;
}

.forgot-password:hover {
    text-decoration: underline;
}

/* 按钮 */
.login-button {
    padding: 0.75rem;
    background-color: #4285f4;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    font-weight: 500;
    /* 悬停时，将鼠标光标变成一只手的形状（👆） */
    cursor: pointer;
    /* 鼠标悬停到按钮时，背景色会在 0.3 秒内从 #4285f4 渐变到 #3367d6 */
    transition: background-color 0.3s;
}

.login-button:hover {
    background-color: #3367d6;
}

.login-button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
}

.login-footer {
    margin-top: 1.5rem;
    text-align: center;
    font-size: 0.9rem;
    color: #555;
}

.login-footer a {
    color: #4285f4;
    text-decoration: none;
}

.login-footer a:hover {
    text-decoration: underline;
}
</style>